package com.concerneyes.glasses;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.concerneyes.R;
import com.concerneyes.glasses.adapter.ViewPagerAdapter;
import com.concerneyes.glasses.view.GlassesAgreementView;
import com.concerneyes.glasses.view.GlassesDetailView;
import com.concerneyes.glasses.model.GlassesDetailModel;
import com.concerneyes.glasses.model.GlassesItemModel;
import com.concerneyes.glasses.task.GlassesImpl;
import com.concerneyes.glasses.task.GlassesListener;
import com.concerneyes.mine.Task.OrderImpl;
import com.concerneyes.mine.Task.OrderListener;
import com.concerneyes.mine.model.OrderSubmit;
import com.concerneyes.pay.ConfirmInfoActivity;
import com.concerneyes.pay.DialogPay;
import com.concerneyes.rentbarsecond.db.GlassesDetailModelForDao;
import com.concerneyes.rentbarsecond.db.RentBarDao;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import common.AbsActivity;
import common.AbsBaseView;
import common.PagerTask;
import http.JsonMap;
import util.ActivityUtil;
import util.ToastHelper;
import view.PagerSlidingTabStrip;
import view.PointerView;
import view.ViewPagerForScrollView;

/**
 * 产品详情
 */

public class GlassesDetail extends AbsActivity implements View.OnClickListener,
        ViewPager.OnPageChangeListener, GlassesListener, GlassesDetailView.OnImagesListener, OrderListener, DialogPay.PaySuccessListener {
    private ViewPagerForScrollView vp_glasses_top;
    private ViewPagerForScrollView vp_glasses_bottom;
    private PagerSlidingTabStrip tabStrip;
    private TextView add_rentBar, pay_now;
    private ViewPagerAdapter pagerAdapter;
    private ViewPagerAdapter pagerAdapter_top;
    private PointerView dotView;
    private PagerTask pagerTask;
    private List<AbsBaseView> flList;
    private String productNo;
    private String frameColors;
    private RelativeLayout ll_top_play;
    private GlassesImpl impl;
    private OrderImpl orderImpl;
    private HashMap<String, String> data;
    private String colorCode = null;
    private String refractiveId = null;
    private int orderId;
    public static final int MIN_CLICK_DELAY_TIME = 3000;
    private long lastClickTime = 0;
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_classes_dateil);
        setTitle(R.string.product);
        getRightText().setVisibility(View.VISIBLE);
        getRightText().setText(R.string.try_it);
        productNo = getIntent().getExtras().getString("productNo");
        frameColors = getIntent().getExtras().getString("frameColors");
        initView();
    }

    @Override
    public void onRightTextAction(View v) {
        super.onRightTextAction(v);
        startActivity(new Intent(GlassesDetail.this, TryItActivity.class));
    }

    private void initView() {
        ll_top_play = (RelativeLayout) findViewById(R.id.ll_top_play);
        vp_glasses_top = (ViewPagerForScrollView) findViewById(R.id.vp_glasses_top);
        vp_glasses_bottom = (ViewPagerForScrollView) findViewById(R.id.vp_glasses_bottom);
        tabStrip = (PagerSlidingTabStrip) findViewById(R.id.indicator_glasses);
        add_rentBar = (TextView) findViewById(R.id.add_rentbar);
        pay_now = (TextView) findViewById(R.id.pay_now);
        dotView = (PointerView) findViewById(R.id.dotView);
        add_rentBar.setOnClickListener(this);
        pay_now.setOnClickListener(this);
        final int height = this.getWindowManager().getDefaultDisplay().getHeight();
        impl = new GlassesImpl(this);
        colorCode = frameColors;
        impl.glassesInfo(productNo, frameColors);
        orderImpl = new OrderImpl(this);
        setBottomViewPager();
    }

    //顶部的ViewPager配置
    private void setTopViewPager(ArrayList<String> imagePath) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int heightPixels = dm.heightPixels / 2;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, heightPixels);
        ll_top_play.setLayoutParams(params);
        final ArrayList<AbsBaseView> list = new ArrayList<>();
        for (int i = 0; i < imagePath.size(); i++) {
            list.add(new GlassesViewPage(this, imagePath.get(i)));
        }
        pagerAdapter_top = new ViewPagerAdapter(this, list);
        initViewPager(vp_glasses_top);
        vp_glasses_top.setAdapter(pagerAdapter_top);
        vp_glasses_top.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                dotView.showWhitch(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        dotView.show(pagerAdapter_top.getCount());
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                pagerTask = new PagerTask(vp_glasses_top, pagerAdapter_top.getCount());
                pagerTask.start();
            }
        }, 1500);
    }

    //底部的ViewPager配置
    private void setBottomViewPager() {
        tabStrip.setTextColor(getResources().getColor(R.color.gray));
        tabStrip.setOnClickListener(this);
        flList = new ArrayList<>();
        flList.add(new GlassesDetailView(this));
        flList.add(new GlassesAgreementView(this));
        flList.add(new GlassesAgreementView(this));
        pagerAdapter = new ViewPagerAdapter(this, flList);

        vp_glasses_bottom.setAdapter(pagerAdapter);
        tabStrip.setViewPager(vp_glasses_bottom);
        tabStrip.setOnPageChangeListener(this);

        GlassesDetailView fragment = (GlassesDetailView) flList.get(0);
        data = new HashMap<>();
        data.put("productNo", productNo);
        data.put("frameColors", frameColors);
        fragment.loadData(data);
    }

    private void initViewPager(ViewPager vp) {
        vp.setOffscreenPageLimit(10);
        //左右都缩进一个合适的值
        vp.setPageMargin((int) (-getResources().getDisplayMetrics().widthPixels / 3 * 2 * 0.5));
        //中间大 ,两边大小渐变的动画变化,最大1.4倍
        vp.setPageTransformer(true, new ViewPager.PageTransformer() {
            public void transformPage(View page, float position) {
                if (position < -1) {
                    // This page is way off-screen to the left.
                } else if (position <= 1) {
                    if (position < 0) {
                        if (position < -0.4f)
                            position = -0.4f;
                        page.setScaleY(1.4f + position);
                        page.setScaleX(1.4f + position);
                    } else {
                        if (position > 0.4)
                            position = 0.4f;
                        page.setScaleY(1.4f - position);
                        page.setScaleX(1.4f - position);
                    }
                } else {
                    // This page is way off-screen to the right.
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.indicator_glasses:
                ToastHelper.getInstance()._toast("点击....");
                break;
            case R.id.pay_now:
                orderImpl.submitOrder(colorCode, refractiveId, productNo);
                break;
            case R.id.add_rentbar:
                long currentTime = Calendar.getInstance().getTimeInMillis();
                if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
                    lastClickTime = currentTime;
                    addRentDb();
                }
                break;
        }
    }

    private void addRentDb() {
        String price = null;
        GlassesDetailModelForDao modelForDao = new GlassesDetailModelForDao();
        modelForDao.setCategoryId(detailModel.getCategoryId());
        modelForDao.setFrameColorCode(colorCode);
        for (int i = 0; i < detailModel.getColorList().size(); i++) {
            if (detailModel.getColorList().get(i).getCode().equals(colorCode)) {
                modelForDao.setFrameColor(detailModel.getColorList().get(i).getName());
            }
        }
        modelForDao.setProductNo(detailModel.getProductNo());
        modelForDao.setRefractiveId(refractiveId);
        for (int i = 0; i < detailModel.getRefractiveList().size(); i++) {
            if (String.valueOf(detailModel.getRefractiveList().get(i).getId()).equals(refractiveId)) {
                modelForDao.setRefractivetitle(detailModel.getRefractiveList().get(i).getTitle());
                price = detailModel.getRefractiveList().get(i).getPrice();
            }
        }
        modelForDao.setImgPath(detailModel.getImgList().get(0).getPath());
        modelForDao.setTitle(detailModel.getTitle());
        modelForDao.setTotalPrice(String.valueOf(Double.valueOf(detailModel.getPrice()) + Double.valueOf(price)));
        new RentBarDao(this).add(modelForDao);
        Toast.makeText(this,R.string.add_rentbar_sucess,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        AbsBaseView baseView = flList.get(position);
        baseView.loadData(data);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    //======================================================
    @Override
    public void onCategoryListSuccess(List<JsonMap> datas) {

    }

    @Override
    public void onCategoryListFail() {

    }

    @Override
    public void onGlassesListSuccess(GlassesItemModel datas) {

    }

    @Override
    public void onGlassesListFail() {

    }

    private GlassesDetailModel detailModel;

    @Override
    public void onGlassesInfoSuccess(GlassesDetailModel datas) {
        this.detailModel = datas;
        ArrayList<String> imgs = new ArrayList<>();
        for (int i = 0; i < datas.getImgList().size(); i++) {
            imgs.add(datas.getImgList().get(i).getPath());
        }
        setTopViewPager(imgs);
        refractiveId = String.valueOf(datas.getRefractiveList().get(0).getId());
    }

    @Override
    public void onGlassesInfoFail() {
    }

    //======================================================
    @Override
    public void changeImages(String code) {
        this.colorCode = code;
        if (!TextUtils.isEmpty(code)) {
            impl.glassesInfo(productNo, code);
        }
    }

    @Override
    public void changeRefractive(String id) {
        this.refractiveId = id;
    }

    //======================================================
    @Override
    public void onSubmitSuccess(OrderSubmit msg) {
        orderId = msg.getId();
        new DialogPay(this, msg.getOrderNo(), this);
    }

    @Override
    public void onSubmitFail() {

    }

    @Override
    public void oncompleteSuccess() {

    }

    @Override
    public void oncompleteFail() {

    }

    @Override
    public void onDeliverSuccess() {

    }

    @Override
    public void onDeliverFail() {

    }

    @Override
    public void onPaySuccess(String resultStatus) {
        Bundle bundle = new Bundle();
        bundle.putInt("orderId", orderId);
        ActivityUtil.setIntent(this, ConfirmInfoActivity.class, bundle);
        finish();
    }

    @Override
    public void onPayFail() {

    }
}
